package org.ztest.spring.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository("IMG_DAO")
public class ImageDao
{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void save(Image image) {
        getJdbcTemplate().update(
                "INSERT INTO img (id, emoji, data) VALUES(?,?,?) " + "ON DUPLICATE KEY UPDATE id=?, emoji=?, data=?",
                image.getId(), image.getEmoji(), image.getData(), image.getId(), image.getEmoji(), image.getData());
    }
    
    public void delete(Image image) {
        getJdbcTemplate().update("DELETE FROM img WHERE id=?", image.getId());
    }

    public void delete(int id) {
        getJdbcTemplate().update("DELETE FROM img WHERE id=?", id);
    }

    public Image find(int id) {
        return getJdbcTemplate().query("SELECT * FROM img WHERE id=?", new Object[] { id }, extrator);
    }

    public List<Image> findAll() {
        return getJdbcTemplate().query("SELECT * FROM img", new RowMapper<Image>() {
            @Override
            public Image mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rsToEntity(rs);
            }
        });
    }
    
    public int getMaxId() {
        return getJdbcTemplate().queryForObject("SELECT IFNULL(MAX(Id), 0) FROM img", Integer.class);
    }
    
    public String getEmoji() {
        return getJdbcTemplate().queryForObject("SELECT emoji FROM img WHERE id = 0", String.class);
    }

    public static ResultSetExtractor<Image> extrator = new ResultSetExtractor<Image>() {
        @Override
        public Image extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (!rs.next()) {
                return null;
            }

            return rsToEntity(rs);
        }
    };

    public static Image rsToEntity(ResultSet rs) throws SQLException {
        Image img = new Image();
        img.setId(rs.getInt("id"));
        img.setData(rs.getString("data"));
        img.setEmoji(rs.getString("emoji"));
        return img;
    }
}
